<?php

require_once (dirname(__FILE__)."/api.php");

global $inc;

if(isset($_GET['plugins'])) {
	header('Content-Type: text/javascript; charset=utf-8');
	echo getPlugins();
	
} else {
	
	// list all js files and put mootools into first pos
	$dirjs = opendir($inc."/js/");
	$jsfiles = array('mootools.js');
	while (false !== ($file = readdir($dirjs))) {
		if(!ereg("^\.",$file) && !ereg("^mootools",strtolower($file))) $jsfiles[] = $file;
	}
	
	global $jsconfig;
	
	// return everything as single file
	if (isset($_GET['compressed'])) {
		header ("content-type: text/javascript; charset=UTF-8");
		
		$content = "//config
	var skinpath = '".$_SESSION['joel']->skinpath."';
	var sessionID = '".session_id()."';\n";
		foreach($jsconfig as $k => $v) {$content .= '	var '.$k."='".$v."';\n\n"; }

		foreach($jsfiles as $file) {
			$content .= "\n//js/".$file."\n".file_get_contents("js/".$file);
		}
		
		//$content = trim(preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!',' ', $content));
		$content .= "\n\n//plugins\n".getPlugins();
		
		echo $content;
		
	} else {
		// read all files from js directory to include
		if(DEV) {
			echo "<script type=\"text/javascript\">\n";
			echo "		var skinpath = '".$_SESSION['joel']->skinpath."';\n";
			echo "		var sessionID = '".session_id()."';\n";
			foreach($jsconfig as $k => $v) { echo '		var '.$k."='".$v."';\n";	 }
			echo "	</script>\n";
			foreach($jsfiles as $file) {
				echo "	<script type=\"text/javascript\" src=\"js/$file\"></script>\n";
			}
			echo "	<script type=\"text/javascript\" src=\"scripts.php?plugins=1\"></script>\n";

		} else {
			echo "	<script type=\"text/javascript\" src=\"scripts.php?compressed=1\"></script>\n";
		}
	}
}

function getPlugins() {
	//  now load all plugin scripts 
	$plugins = '';
	$pluginslist = '';
	foreach($_SESSION['joel']->pluginslist as $plugin) {
		$file = $_SESSION['joel']->basedir."/plugins/".$plugin."/plugin.js";
		if(file_exists($file)) {
			$content = file_get_contents($file);
			$content = trim(preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!','', $content));
			$pluginname = trim(str_replace('var','',substr($content,0,strpos($content, '='))));
			$plugins .= $pluginname.":". substr($content, strpos($content,'{'), strrpos($content,'}')-strpos($content,'{')+1).",\n\n";
		}
	}
	
	return "var plugins={".substr(str_replace(';;',';',$plugins),0,-3)."}; ";

}


?>
